<template>
  <el-card class="order-container">
    <template #header>
      <el-config-provider :locale="zhCn">
        <div class="header">
          <el-input
              style="width: 200px; margin-right: 10px"
              placeholder="请输入订单号"
              v-model="state.orderNo"
              @change="handleOption"
              clearable
          />
          <el-select @change="handleOption" v-model="state.orderStatus" style="width: 200px; margin-right: 10px">
            <el-option
                v-for="item in state.options"
                :key="item.value"
                :label="item.label"
                :value="item.value"
            />
          </el-select>
          <!-- 新增开票状态筛选 -->
          <el-select @change="handleOption" v-model="state.isBill" style="width: 200px; margin-right: 10px" placeholder="发票状态">
            <el-option
                v-for="item in state.billOptions"
                :key="item.value"
                :label="item.label"
                :value="item.value"
            />
          </el-select>
          <!-- 新增创建时间筛选 -->
          <!-- 中文日期选择器 -->
          <el-date-picker
              v-model="state.createTimeRange"
              type="daterange"
              range-separator="至"
              start-placeholder="开始日期"
              end-placeholder="结束日期"
              style="width: 300px; margin-right: 10px"
              @change="handleDateChange"
              value-format="YYYY-MM-DD"
              format="YYYY-MM-DD"
              :unlink-panels="true"
          />
          <el-button type="primary" :icon="HomeFilled" @click="getOrderList()">查询</el-button>
          <el-button type="primary" :icon="HomeFilled" @click="handleConfig()">配货完成</el-button>
          <el-button type="primary" :icon="HomeFilled" @click="handleSend()">出库</el-button>
<!--          <el-button type="danger" :icon="Delete" @click="handleClose()">关闭订单</el-button>-->
          <!-- 新增导出Excel按钮 -->
          <el-button type="success" :icon="Download" @click="handleExportExcel">导出Excel</el-button>
        </div>
      </el-config-provider>
    </template>
    <el-table
        :load="state.loading"
        :data="state.tableData"
        tooltip-effect="dark"
        style="width: 100%"
        @selection-change="handleSelectionChange">
      <el-table-column
          type="selection"
          width="55">
      </el-table-column>
      <el-table-column
          prop="orderNo"
          label="订单号"
      >
      </el-table-column>
      <el-table-column
          prop="totalPrice"
          label="订单总价"
      >
      </el-table-column>
      <el-table-column
          prop="refundStatus"
          label="退款状态"
      >
      </el-table-column>
      <!-- 新增退款原因列 -->
      <el-table-column
          prop="refundReason"
          label="退款原因"
          width="120"
          show-overflow-tooltip
      >
        <template #default="scope">
          <span v-if="scope.row.refundReason">{{ scope.row.refundReason }}</span>
          <span v-else style="color: #ccc">-</span>
        </template>
      </el-table-column>

      <el-table-column
          prop="orderStatus"
          label="订单状态"
      >
        <template #default="scope">
          <span>{{ $filters.orderMap(scope.row.orderStatus) }}</span>
        </template>
      </el-table-column>
      <el-table-column
          prop="payType"
          label="支付方式"
      >
        <template #default='scope'>
          <span v-if="scope.row.payType == 1">支付宝支付</span>
          <span v-else-if="scope.row.payType == 2">微信支付</span>
          <span v-else>未知</span>
        </template>
      </el-table-column>
      <!-- 新增开票状态列 -->
      <el-table-column
          prop="isBill"
          label="发票状态"
          width="100"
      >
        <template #default="scope">
          <el-tag
              :type="getBillTagType(scope.row.isBill)"
              size="small"
          >
            {{ getBillStatusText(scope.row.isBill) }}
          </el-tag>
        </template>
      </el-table-column>
      <el-table-column
          prop="createTime"
          label="创建时间"
      >
      </el-table-column>
      <el-table-column
          label="操作"
          width="280"
      >
        <template #default="scope">
          <!-- 财务管理员只显示财务同意退款按钮 -->
          <template v-if="state.currentUserRole === '财务管理员'">
            <el-popconfirm
                v-if="scope.row.refundStatus == '业务员退款通过'"
                title="确定同意退款吗？"
                @confirm="handleRefund(scope.row.orderNo)"
                confirm-button-text="确定"
                cancel-button-text="取消"
            >
              <template #reference>
                <el-button type="warning" size="small" style="margin-right: 10px">财务同意退款</el-button>
              </template>
            </el-popconfirm>
          </template>

          <!-- 非财务管理员显示其他按钮 -->
          <template v-else>
            <el-popconfirm
                v-if="scope.row.orderStatus == 1"
                title="确定配货完成吗？"
                @confirm="handleConfig(scope.row.orderId)"
                confirm-button-text="确定"
                cancel-button-text="取消"
            >
              <template #reference>
                <a style="cursor: pointer; margin-right: 10px">配货完成</a>
              </template>
            </el-popconfirm>
            <el-popconfirm
                v-if="scope.row.orderStatus == 2"
                title="确定出库吗？"
                @confirm="handleSend(scope.row.orderId)"
                confirm-button-text="确定"
                cancel-button-text="取消"
            >
              <template #reference>
                <a style="cursor: pointer; margin-right: 10px">出库</a>
              </template>
            </el-popconfirm>
            <el-popconfirm
                v-if="!(scope.row.orderStatus == 4 || scope.row.orderStatus < 0)"
                title="确定关闭订单吗？"
                @confirm="handleClose(scope.row.orderId)"
                confirm-button-text="确定"
                cancel-button-text="取消"
            >
<!--              <template #reference>
                <a style="cursor: pointer; margin-right: 10px">关闭订单</a>
              </template>-->
            </el-popconfirm>
            <!-- 业务员同意退款按钮 -->
            <el-popconfirm
                v-if="scope.row.refundStatus == '用户申请退款' && scope.row.orderStatus>0"
                title="确定要同意退款吗？"
                @confirm="handleRefundYwy(scope.row.orderNo)"
                confirm-button-text="确定"
                cancel-button-text="取消"
            >
              <template #reference>
                <el-button type="primary" size="small" style="margin-right: 10px">业务员同意退款</el-button>
              </template>
            </el-popconfirm>
            <!-- 财务同意退款按钮（非财务管理员不显示） -->
            <el-popconfirm
                v-if="scope.row.refundStatus == '业务员退款通过' && scope.row.orderStatus>0 && state.currentUserRole !== '财务管理员'"
                title="确定要退款吗？"
                @confirm="handleRefund(scope.row.orderNo)"
                confirm-button-text="确定"
                cancel-button-text="取消"
            >
<!--              <template #reference>-->
<!--                <a style="cursor: pointer; margin-right: 10px">退款</a>-->
<!--              </template>-->
            </el-popconfirm>
            <!-- 新增同意开票操作 -->
            <el-popconfirm
                v-if="scope.row.isBill == 2"
                title="确定同意开票吗？"
                @confirm="handleApproveInvoice(scope.row.orderNo)"
                confirm-button-text="确定"
                cancel-button-text="取消"
            >
              <template #reference>
                <el-button type="success" size="small" style="margin-right: 10px">同意开票</el-button>
              </template>
            </el-popconfirm>
            <router-link :to="{ path: '/order_detail', query: { id: scope.row.orderId }}">订单详情</router-link>
          </template>
        </template>
      </el-table-column>
    </el-table>
    <el-pagination
        background
        layout="prev, pager, next"
        :total="state.total"
        :page-size="state.pageSize"
        :current-page="state.currentPage"
        @current-change="changePage"
    />
  </el-card>

  <!-- 物流单号弹窗 -->
  <el-dialog
      v-model="state.dialogVisible"
      title="填写物流信息"
      width="400px"
      :before-close="handleDialogClose"
  >
    <el-form :model="state.shipForm" label-width="80px">
      <el-form-item label="物流单号" required>
        <el-input
            v-model="state.shipForm.trackingNumber"
            placeholder="请输入物流单号"
            clearable
        />
      </el-form-item>
      <el-form-item label="寄件人手机尾号">
        <el-input
            v-model="state.shipForm.sendPhone"
            placeholder="寄件人手机尾号"
            clearable
        />
      </el-form-item>
      <el-form-item label="物流公司">
        <el-input
            v-model="state.shipForm.shippingCompany"
            placeholder="请输入物流公司"
            clearable
        />
      </el-form-item>
    </el-form>
    <template #footer>
      <span class="dialog-footer">
        <el-button @click="state.dialogVisible = false">取消</el-button>
        <el-button type="primary" @click="confirmSend">确定出库</el-button>
      </span>
    </template>
  </el-dialog>
</template>

<script setup>
import { onMounted, reactive } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import { HomeFilled, Delete, Download } from '@element-plus/icons-vue'
import zhCn from 'element-plus/es/locale/lang/zh-cn'

import axios from '@/utils/axios'

const state = reactive({
  loading: false,
  tableData: [], // 数据列表
  multipleSelection: [], // 选中项
  total: 0, // 总条数
  currentPage: 1, // 当前页
  pageSize: 10, // 分页大小
  orderNo: '', // 订单号
  orderStatus: '', // 订单状态
  isBill: '', // 开票状态筛选
  createTimeRange: [], // 创建时间范围
  startTime: '', // 开始时间
  endTime: '', // 结束时间
  dialogVisible: false, // 物流弹窗显示
  pendingOrderIds: [], // 待出库的订单ID列表
  shipForm: {
    trackingNumber: '', // 物流单号
    shippingCompany: '', // 物流公司
    sendPhone: '' // 寄件人手机尾号
  },
  currentUserRole: '', // 当前用户角色
  // 订单状态筛选项
  options: [{
    value: '',
    label: '全部'
  }, {
    value: 0,
    label: '待支付'
  }, {
    value: 1,
    label: '已支付'
  }, {
    value: 2,
    label: '配货完成'
  }, {
    value: 3,
    label: '出库成功'
  }, {
    value: 4,
    label: '交易成功'
  }, {
    value: -1,
    label: '手动关闭'
  }, {
    value: -2,
    label: '超时关闭'
  }, {
    value: -3,
    label: '商家关闭'
  }],
  // 开票状态筛选项
  billOptions: [{
    value: '',
    label: '全部发票状态'
  }, {
    value: 1,
    label: '未开票'
  }, {
    value: 2,
    label: '开票申请中'
  }, {
    value: 3,
    label: '商家同意开票'
  }, {
    value: 4,
    label: '已开票'
  }]
})

// 获取当前用户信息
const getCurrentUser = () => {
  // 这里根据你的实际用户信息存储方式获取当前用户角色
  // 假设用户信息存储在 localStorage 或 Vuex 中
  const roleName = localStorage.getItem('roleName')
  state.currentUserRole = roleName
  console.log('当前用户角色:', state.currentUserRole)
}

// 获取开票状态文本
const getBillStatusText = (isBill) => {
  switch (isBill) {
    case 1: return '未开票'
    case 2: return '申请中'
    case 3: return '已同意'
    case 4: return '已开票'
    default: return '未知'
  }
}

// 获取开票状态标签类型
const getBillTagType = (isBill) => {
  switch (isBill) {
    case 1: return 'info'
    case 2: return 'warning'
    case 3: return 'primary'
    case 4: return 'success'
    default: return 'info'
  }
}

// 日期选择变化处理
const handleDateChange = (val) => {
  if (val && val.length === 2) {
    state.startTime = val[0]
    state.endTime = val[1]
  } else {
    state.startTime = ''
    state.endTime = ''
  }
  state.currentPage = 1
  getOrderList()
}

// 初始化获取订单列表
onMounted(() => {
  getCurrentUser()
  getOrderList()
})

// 获取列表方法
const getOrderList = () => {
  state.loading = true
  axios.get('/orders', {
    params: {
      pageNumber: state.currentPage,
      pageSize: state.pageSize,
      orderNo: state.orderNo,
      orderStatus: state.orderStatus,
      isBill: state.isBill,
      startTime: state.startTime, // 新增开始时间参数
      endTime: state.endTime // 新增结束时间参数
    }
  }).then(res => {
    state.tableData = res.list
    state.total = res.totalCount
    state.currentPage = res.currPage
    state.loading = false
  })
}

// 触发过滤项方法
const handleOption = () => {
  state.currentPage = 1
  getOrderList()
}

// checkbox 选择项
const handleSelectionChange = (val) => {
  state.multipleSelection = val
}

// 翻页方法
const changePage = (val) => {
  state.currentPage = val
  getOrderList()
}

// 导出订单方法
async function handleExportExcel() {
  try {
    await ElMessageBox.confirm('确定要导出订单数据吗？', '导出确认', {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning'
    })

    const params = {
      orderNo: state.orderNo || undefined,
      orderStatus: state.orderStatus !== '' ? state.orderStatus : undefined,
      isBill: state.isBill !== '' ? state.isBill : undefined,
      startTime: state.startTime || undefined,
      endTime: state.endTime || undefined
    }

    console.log('导出参数:', params)

    // 构建查询字符串
    const formData = new FormData()
    Object.keys(params).forEach(key => {
      if (params[key] !== undefined && params[key] !== null) {
        formData.append(key, params[key])
      }
    })

    // 方法1: 使用 window.open (推荐用于 POST 请求)
    const queryString = Object.keys(params)
        .filter(key => params[key] !== undefined && params[key] !== null)
        .map(key => `${encodeURIComponent(key)}=${encodeURIComponent(params[key])}`)
        .join('&')

    const url = `http://172.26.200.76:28019/manage-api/v1/exportOrder?${queryString}`
    console.log('导出URL:', url)

    // 新窗口打开导出
    window.open(url, '_blank')

    ElMessage.success('导出请求已发送，请稍候...')

  } catch (error) {
    console.error('导出失败:', error)
    if (error !== 'cancel') { // 不是用户取消的情况
      ElMessage.error('导出失败: ' + (error.message || '未知错误'))
    }
  }
}

// 从响应头中获取文件名
const getFileNameFromResponse = (response) => {
  const contentDisposition = response.headers['content-disposition']
  if (contentDisposition) {
    const filenameMatch = contentDisposition.match(/filename=(.+)/)
    if (filenameMatch && filenameMatch.length === 2) {
      return decodeURIComponent(filenameMatch[1])
    }
  }
  return null
}

// 配货方法
const handleConfig = (id) => {
  let params
  // 当个配置
  if (id) {
    params = [id]
  } else {
    if (!state.multipleSelection.length) {
      console.log('state.multipleSelection', state.multipleSelection.length)
      ElMessage.error('请选择项')
      return
    }
    // 多选配置
    params = state.multipleSelection.map(i => i.orderId)
  }
  axios.put('/orders/checkDone', {
    ids: params
  }).then(() => {
    ElMessage.success('配货成功')
    getOrderList()
  })
}
// 出库方法
const handleSend = (id) => {
  let params
  if (id) {
    params = [id]
  } else {
    if (!state.multipleSelection.length) {
      ElMessage.error('请选择项')
      return
    }
    params = state.multipleSelection.map(i => i.orderId)
  }

  // 保存待出库的订单ID
  state.pendingOrderIds = params
  // 重置表单
  state.shipForm.trackingNumber = 'SF3288184741946'
  state.shipForm.shippingCompany = '顺丰物流'
  state.shipForm.sendPhone = '6996'

  // 显示物流单号弹窗
  state.dialogVisible = true
}
// 确认出库
const confirmSend = () => {
  if (!state.shipForm.trackingNumber.trim()) {
    ElMessage.error('请输入物流单号')
    return
  }

  if (!state.shipForm.sendPhone.trim()) {
    ElMessage.error('请输入寄件人手机尾号')
    return
  }

  axios.put('/orders/checkOut', {
    ids: state.pendingOrderIds,
    trackingNo: state.shipForm.trackingNumber,
    sendPhone:state.shipForm.sendPhone,
    shippingCompany: state.shipForm.shippingCompany
  }).then(() => {
    ElMessage.success('出库成功')
    state.dialogVisible = false
    getOrderList()
  }).catch(error => {
    ElMessage.error('出库失败：' + (error.response?.data?.message || error.message))
  })
}
// 关闭弹窗
const handleDialogClose = (done) => {
  state.dialogVisible = false
}
// 关闭订单方法
const handleClose = (id) => {
  let params
  if (id) {
    params = [id]
  } else {
    if (!state.multipleSelection.length) {
      ElMessage.error('请选择项')
      return
    }
    params = state.multipleSelection.map(i => i.orderId)
  }
  axios.put('/orders/close', {
    ids: params
  }).then(() => {
    ElMessage.success('关闭成功')
    getOrderList()
  })
}

// 新增业务员同意退款方法
const handleRefundYwy = (orderNo) => {
  axios.put('/orders/refundYwyOrder', {
    orderNo: orderNo
  }).then(() => {
    ElMessage.success('业务员同意退款成功')
    getOrderList()
  }).catch(error => {
    ElMessage.error('业务员同意退款失败：' + (error.response?.data?.message || error.message))
  })
}

// 财务同意退款方法
const handleRefund = (orderNo) => {
  axios.put('/orders/refundOrder', {
    orderNo: orderNo
  }).then(() => {
    ElMessage.success('退款操作成功')
    getOrderList()
  }).catch(error => {
    ElMessage.error('退款操作失败：' + (error.response?.data?.message || error.message))
  })
}

// 新增同意开票方法
const handleApproveInvoice = (orderNo) => {
  axios.put('/orders/approveInvoice', {
    orderNo: orderNo
  }).then(() => {
    ElMessage.success('同意开票成功')
    getOrderList()
  }).catch(error => {
    ElMessage.error('同意开票失败：' + (error.response?.data?.message || error.message))
  })
}
</script>
